<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联订单" prop="orderNo">
        <el-select v-model="queryParams.orderNo" placeholder="请选择关联订单" clearable @keyup.enter.native="handleQuery">
          <el-option
            v-for="order in orderList"
            :key="order.orderNo"
            :label="order.orderNo + ' - ¥' + order.totalAmount"
            :value="order.orderNo">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态" prop="payStatus">
        <el-select v-model="queryParams.payStatus" placeholder="请选择支付状态" clearable @keyup.enter.native="handleQuery">
          <el-option label="待支付" :value="0"></el-option>
          <el-option label="支付成功" :value="1"></el-option>
          <el-option label="支付失败" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="第三方支付流水号" prop="tradeNo">
        <el-input
          v-model="queryParams.tradeNo"
          placeholder="请输入第三方支付流水号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付成功时间" prop="payTime">
        <el-date-picker clearable
          v-model="queryParams.payTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择支付成功时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['car:pay:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['car:pay:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['car:pay:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['car:pay:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="payList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="支付记录ID" align="center" prop="id" />
      <el-table-column label="关联订单编号" align="center" prop="orderNo" />
      <el-table-column label="支付金额" align="center" prop="payAmount">
        <template slot-scope="scope">
          <span style="color: #E6A23C; font-weight: bold;">¥{{ scope.row.payAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="payType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.payType === 'wechat'" type="success">微信支付</el-tag>
          <el-tag v-else-if="scope.row.payType === 'alipay'" type="primary">支付宝</el-tag>
          <el-tag v-else-if="scope.row.payType === 'unionpay'" type="info">银联支付</el-tag>
          <span v-else>{{ scope.row.payType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="payStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.payStatus === 0" type="warning">待支付</el-tag>
          <el-tag v-else-if="scope.row.payStatus === 1" type="success">支付成功</el-tag>
          <el-tag v-else-if="scope.row.payStatus === 2" type="danger">支付失败</el-tag>
          <span v-else>{{ scope.row.payStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="第三方支付流水号" align="center" prop="tradeNo" />
      <el-table-column label="支付成功时间" align="center" prop="payTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['car:pay:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['car:pay:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改支付记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联订单" prop="orderNo">
              <el-select v-model="form.orderNo" placeholder="请选择关联订单" filterable @change="onOrderChange">
                <el-option
                  v-for="order in orderList"
                  :key="order.orderNo"
                  :label="order.orderNo"
                  :value="order.orderNo">
                  <div style="display: flex; justify-content: space-between;">
                    <span>{{ order.orderNo }}</span>
                    <span style="color: #8492a6; font-size: 13px;">￥{{ order.totalAmount }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付金额" prop="payAmount">
              <el-input-number v-model="form.payAmount" :precision="2" :min="0.01" :max="999999" placeholder="请输入支付金额" style="width: 100%">
                <template slot="append">元</template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付方式" prop="payType">
              <el-select v-model="form.payType" placeholder="请选择支付方式">
                <el-option label="微信支付" value="wechat">
                  <i class="el-icon-chat-dot-square" style="color: #07C160;"></i> 微信支付
                </el-option>
                <el-option label="支付宝" value="alipay">
                  <i class="el-icon-wallet" style="color: #1677FF;"></i> 支付宝
                </el-option>
                <el-option label="银联支付" value="unionpay">
                  <i class="el-icon-bank-card" style="color: #E74C3C;"></i> 银联支付
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付状态" prop="payStatus">
              <el-select v-model="form.payStatus" placeholder="请选择支付状态">
                <el-option label="待支付" :value="0"></el-option>
                <el-option label="支付成功" :value="1"></el-option>
                <el-option label="支付失败" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="支付流水号" prop="tradeNo">
          <el-input v-model="form.tradeNo" placeholder="系统自动生成" readonly>
            <el-button slot="append" icon="el-icon-refresh" @click="refreshTradeNo">重新生成</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="支付成功时间" prop="payTime" v-if="form.payStatus === 1">
          <el-date-picker clearable
            v-model="form.payTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择支付成功时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPay, getPay, delPay, addPay, updatePay, getFormData, generateTradeNo } from "@/api/car/pay"

export default {
  name: "Pay",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 支付记录表格数据
      payList: [],
      // 订单列表
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        payAmount: null,
        payType: null,
        payStatus: null,
        tradeNo: null,
        payTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderNo: [
          { required: true, message: "请选择关联订单", trigger: "change" }
        ],
        payAmount: [
          { required: true, message: "支付金额不能为空", trigger: "blur" },
          { type: 'number', min: 0.01, message: "支付金额必须大于0", trigger: "blur" }
        ],
        payType: [
          { required: true, message: "请选择支付方式", trigger: "change" }
        ],
        payStatus: [
          { required: true, message: "请选择支付状态", trigger: "change" }
        ],
        tradeNo: [
          { required: true, message: "支付流水号不能为空", trigger: "blur" }
        ],
        payTime: [
          { validator: this.validatePayTime, trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.loadFormData()
  },
  methods: {
    /** 加载表单数据 */
    loadFormData() {
      getFormData().then(response => {
        this.orderList = response.data.orderList || []
      })
    },
    /** 查询支付记录列表 */
    getList() {
      this.loading = true
      listPay(this.queryParams).then(response => {
        this.payList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNo: null,
        payAmount: null,
        payType: null,
        payStatus: 0,
        tradeNo: '',
        payTime: null
      }
      this.resetForm("form")
    },
    /** 订单选择变化事件 */
    onOrderChange(orderNo) {
      const order = this.orderList.find(o => o.orderNo === orderNo)
      if (order) {
        // 自动填充支付金额为订单总金额
        this.form.payAmount = order.totalAmount
      }
    },
    /** 重新生成支付流水号 */
    refreshTradeNo() {
      generateTradeNo().then(response => {
        console.log('重新生成API响应:', response)
        let tradeNo = null
        if (response && typeof response === 'object') {
          if (response.data) {
            tradeNo = response.data
          } else if (response.code === 200) {
            tradeNo = response.result || response.content
          }
        } else if (typeof response === 'string') {
          tradeNo = response
        }
        
        // 确保tradeNo是字符串
        if (tradeNo) {
          this.form.tradeNo = String(tradeNo)
          this.$message.success('支付流水号已重新生成')
          console.log('支付流水号生成成功:', String(tradeNo))
          console.log('tradeNo类型:', typeof String(tradeNo))
          this.$forceUpdate()
        } else {
          this.generateLocalTradeNo()
        }
      }).catch(error => {
        console.error('生成支付流水号失败:', error)
        this.generateLocalTradeNo()
      })
    },
    /** 生成本地支付流水号 */
    generateLocalTradeNo() {
      const timestamp = new Date().toISOString().replace(/[-T:.Z]/g, '').slice(0, 14)
      const randomNum = String(Math.floor(Math.random() * 1000000)).padStart(6, '0')
      const tradeNo = 'PAY' + timestamp + randomNum
      this.form.tradeNo = tradeNo
      this.$message.warning('使用本地生成的支付流水号')
      console.log('使用本地支付流水号:', tradeNo)
      console.log('本地tradeNo类型:', typeof tradeNo)
      this.$forceUpdate()
    },
    /** 验证支付时间 */
    validatePayTime(rule, value, callback) {
      if (this.form.payStatus === 1 && (!value || value.trim() === '')) {
        callback(new Error('支付状态为成功时，必须选择支付成功时间'))
      } else {
        callback()
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加支付记录"
      
      // 延迟执行，确保对话框完全打开后再生成支付流水号
      this.$nextTick(() => {
        // 先使用本地生成的流水号，确保界面有内容显示
        const localTimestamp = new Date().toISOString().replace(/[-T:.Z]/g, '').slice(0, 14)
        const localRandomNum = String(Math.floor(Math.random() * 1000000)).padStart(6, '0')
        const localTradeNo = 'PAY' + localTimestamp + localRandomNum
        this.form.tradeNo = localTradeNo
        this.form.payStatus = 0
        
        // 尝试从后端获取流水号
        generateTradeNo().then(response => {
          console.log('新增API响应:', response)
          let tradeNo = null
          if (response && typeof response === 'object') {
            if (response.data) {
              tradeNo = response.data
            } else if (response.code === 200) {
              tradeNo = response.result || response.content
            }
          } else if (typeof response === 'string') {
            tradeNo = response
          }
          
          if (tradeNo && String(tradeNo) !== localTradeNo) {
            this.form.tradeNo = String(tradeNo)
            console.log('新增支付记录，API生成流水号:', String(tradeNo))
            console.log('API tradeNo类型:', typeof String(tradeNo))
            this.$forceUpdate()
          } else {
            console.log('新增支付记录，使用本地流水号:', localTradeNo)
          }
        }).catch(error => {
          console.error('生成支付流水号失败:', error)
          console.log('新增支付记录，保持本地流水号:', localTradeNo)
        })
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPay(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改支付记录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 额外的业务逻辑验证
          if (this.form.payStatus === 1 && (!this.form.payTime || this.form.payTime.trim() === '')) {
            this.$modal.msgError("支付状态为成功时，必须选择支付成功时间")
            return
          }
          
          // 处理表单数据，确保数据格式正确
          const formData = { ...this.form }
          
          // 确保tradeNo是字符串类型
          if (formData.tradeNo && typeof formData.tradeNo === 'object') {
            formData.tradeNo = formData.tradeNo.toString()
          }
          
          // 确保orderNo是字符串类型
          if (formData.orderNo && typeof formData.orderNo === 'object') {
            formData.orderNo = formData.orderNo.toString()
          }
          
          // 确保payType是字符串类型
          if (formData.payType && typeof formData.payType === 'object') {
            formData.payType = formData.payType.toString()
          }
          
          // 确保数值类型正确
          if (formData.payAmount && typeof formData.payAmount === 'string') {
            formData.payAmount = parseFloat(formData.payAmount)
          }
          
          if (formData.payStatus && typeof formData.payStatus === 'string') {
            formData.payStatus = parseInt(formData.payStatus)
          }
          
          // 如果支付时间为空字符串，设置为null
          if (formData.payTime === '' || formData.payTime === undefined) {
            formData.payTime = null
          }
          
          // 如果支付状态不是成功，清空支付时间
          if (formData.payStatus !== 1) {
            formData.payTime = null
          }
          
          console.log('提交的支付记录数据:', formData)
          console.log('tradeNo类型:', typeof formData.tradeNo, '值:', formData.tradeNo)
          
          const loading = this.$loading({
            lock: true,
            text: '处理中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          
          if (formData.id != null) {
            updatePay(formData).then(response => {
              loading.close()
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            }).catch(error => {
              loading.close()
              console.error('修改错误详情:', error)
              this.$modal.msgError("修改失败：" + (error.msg || error.message || "未知错误"))
            })
          } else {
            addPay(formData).then(response => {
              loading.close()
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(error => {
              loading.close()
              console.error('新增错误详情:', error)
              this.$modal.msgError("新增失败：" + (error.msg || error.message || "未知错误"))
            })
          }
        } else {
          this.$modal.msgError("请检查表单填写是否正确")
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除支付记录（支付页、支付成功页）编号为"' + ids + '"的数据项？').then(function() {
        return delPay(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('car/pay/export', {
        ...this.queryParams
      }, `pay_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.el-input-number {
  width: 100%;
}

.el-select {
  width: 100%;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-dialog__body {
  padding: 20px 20px 10px 20px;
}

.el-tag {
  font-weight: 500;
}

/* 表格中的金额显示 */
.el-table .cell {
  word-break: normal;
}

/* 支付状态标签样式 */
.el-tag.el-tag--warning {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
}

.el-tag.el-tag--primary {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
}

.el-tag.el-tag--success {
  background-color: #f0f9ff;
  border-color: #c6f7e9;
  color: #67c23a;
}

.el-tag.el-tag--danger {
  background-color: #fef0f0;
  border-color: #fbc4c4;
  color: #f56c6c;
}

.el-tag.el-tag--info {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

/* 表单布局优化 */
.el-row {
  margin-bottom: 0;
}

.el-col {
  padding-right: 10px;
  padding-left: 10px;
}

/* 只读输入框样式 */
.el-input.is-disabled .el-input__inner {
  background-color: #f8f9fa;
  border-color: #e9ecef;
  color: #495057;
}

/* 下拉选项样式优化 */
.el-select-dropdown__item {
  height: auto;
  line-height: 1.4;
  padding: 8px 20px;
}

/* 支付方式图标样式 */
.el-option .el-icon-chat-dot-square {
  margin-right: 8px;
}

.el-option .el-icon-wallet {
  margin-right: 8px;
}

.el-option .el-icon-bank-card {
  margin-right: 8px;
}

/* 金额显示样式 */
.pay-amount {
  font-weight: bold;
  font-size: 14px;
}
</style>
